package lu.med.praxiswahl.wahlumed.client.rechnungen;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
import lu.med.praxiswahl.wahlumed.client.utilities.ColumnWidthControler;
import lu.med.praxiswahl.wahlumed.client.utilities.UniCode;
import lu.med.praxiswahl.wahlumed.client.wclient.Main;

/**
 * 
 * @author Lars Holger Roth
 */
public class RechnungenTable extends JTable implements ActionListener,
		RechnungenModelListener {
	/**
     * 
     */
	private static final long serialVersionUID = -832809076589677174L;
	private RechnungenTableModel model;

	private ColumnWidthControler c;
	private boolean isColumnWidthChanged;
	private TableColumn resizedColumn;

	public RechnungenTable(RechnungenTableModel model) {
		this.setModel(model);
		this.model = model;
		this.setRowHeight(30);
		this.selectionModel
				.addListSelectionListener(new RechnungenTableSelectionListener(
						model));
		this.setDefaultRenderer(Object.class, new RechnungenCellRenderer(model));
		// this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent evt) {
				if (evt.isPopupTrigger()) {
					showMenu(evt);
				}
			}
		});

		TableColumn column = null;

		c = new ColumnWidthControler(Main.COLUMNWIDTH_CONFIGURATION_FILE,
				"rechnungtbl", this);

		for (int i = 0; i < 7; i++) {
			column = this.getColumnModel().getColumn(i);
			column.setPreferredWidth(c.getColumnWidth(i));
		}

		this.getColumnModel().addColumnModelListener(
				new TableColumnWidthListener(this));
		this.getTableHeader().addMouseListener(
				new TableHeaderMouseListener(this, c));

	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		model.deleteRow();
	}

	public void showMenu(MouseEvent evt) {
		JPopupMenu menu = new JPopupMenu();
		JMenuItem item = new JMenuItem("Eintrag l" + UniCode.getoe() + "schen");
		item.setIcon(new javax.swing.ImageIcon(getClass().getResource("/table_row_delete.png")));
		item.addActionListener(this);
		menu.add(item);
		menu.show(this, evt.getX(), evt.getY());
	}

	@Override
	public void dataChanged() {
		this.model.fireTableDataChanged();

	}

	public boolean getColumnWidthChanged() {
		return isColumnWidthChanged;
	}

	public void setColumnWidthChanged(boolean widthChanged,
			TableColumn resizedColumn) {
		isColumnWidthChanged = widthChanged;
		this.resizedColumn = resizedColumn;
	}

	public TableColumn getResizedColumn() {
		return resizedColumn;
	}

}
